<template>
  <div id="particles-js" style="height: 100%">
    <div class="logo">
      <img src="../assets/background/logo.png">
    </div>
    <div class="login">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">{{ title }}</h3>
        <el-form-item v-if="tenantEnabled" prop="tenantCode">
          <el-select
            v-model="loginForm.tenantCode"
            filterable
            clearable
            placeholder="租户"
            style="width: 100%"
          >
            <i slot="prefix" class="el-icon-s-home" style="color: #00082e; margin-left: 2px;" />
            <el-option
              v-for="item in tenants"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="isPas ? 'password': 'text'"
            auto-complete="off"
            placeholder="密码"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            <svg-icon v-if="isPas" slot="suffix" icon-class="eye" class="pass-state" @click="isPas=false" />
            <svg-icon v-else slot="suffix" icon-class="eye-open" class="pass-state" @click="isPas=true" />
          </el-input>
        </el-form-item>
        <el-form-item prop="uuid">
          <logo-slider
            :status.sync="status"
            :success-fun="sliderSuccess"
            :error-fun="sliderError"
            :loading="sliderLoading"
          />
          <!--        <el-input-->
          <!--          v-model="loginForm.code"-->
          <!--          auto-complete="off"-->
          <!--          placeholder="验证码"-->
          <!--          @keyup.enter.native="handleLogin"-->
          <!--        >-->
          <!--          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>-->
          <!--          <img :src="codeUrl" slot="suffix" @click="getCode" class="login-code-img"/>-->
          <!--        </el-input>-->
          <!--        <div class="login-code">-->
          <!--          -->
          <!--        </div>-->
        </el-form-item>
        <el-form-item>
          <div style="width: 100%; display: flex;justify-content: space-between">
            <el-checkbox
              v-model="loginForm.rememberMe"
              class="login-checkbox"
              fill="00082d"
              text-color="00082d"
            >记住密码
            </el-checkbox>
          </div>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button
            :disabled="publicKey === ''"
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%; background-color: #00082d; border-color: #00082d"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
      <!--  底部  -->
      <div class="el-login-footer">
        <span style="margin-right: 10px">2020 兆慧科技 版权所有</span>|
        <img src="../assets/background/filing_icon.png" width="16" height="16" style="margin: 0 5px 0 10px">
        <el-link href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=35020602002617" target="_blank" style="color: #00082e; font-size: 12px">
          闽公网安备 35020602002617号
        </el-link>
        <el-link href="https://beian.miit.gov.cn/" target="_blank" style="margin-left: 10px; color: #00082e; font-size: 12px">闽ICP备15013978号-1</el-link>
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg, getPublicKey, getTenants } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import 'particles.js'
// import particlesJson from '@/assets/particles.json'
import LogoSlider from './components/LogoSlider'

export default {
  name: 'Login',
  components: {
    LogoSlider
  },
  data() {
    return {
      /* 滑块状态 */
      status: false,
      /* 加密公匙 */
      publicKey: '',
      isPas: true,
      /* uuid */
      uuid: '',
      title: '',
      codeUrl: '',
      cookiePassword: '',
      loginForm: {
        tenantCode: '',
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        tenantCode: [
          { required: process.env.VUE_APP_TENANT === 'true', trigger: 'change', message: '租户名不能为空' }
        ],
        username: [
          { required: true, trigger: 'blur', message: '用户名不能为空' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' }
        ]
        // code: [{required: true, trigger: "change", message: "验证码不能为空"}]
      },
      loading: false,
      redirect: undefined,
      sliderLoading: false,
      tenants: []
    }
  },
  computed: {
    tenantEnabled() {
      return process.env.VUE_APP_TENANT === 'true'
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    status(val) {
      if (!val) {
        this.publicKey = ''
        this.loginForm.uuid = ''
      }
    }
  },
  created() {
    // this.getCode();
    this.getCookie()
    const defaultSettings = require('../settings.js')
    this.title = defaultSettings.title
    if (this.tenantEnabled) {
      this.getTenants()
    }
  },
  mounted() {
    // particlesJS("particles-js", particlesJson);
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const tenantCode = Cookies.get('tenantCode')
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      if (this.tenantEnabled) {
        this.loginForm.tenantCode = tenantCode || this.loginForm.tenantCode
      }
      this.loginForm.username = username || this.loginForm.username
      this.loginForm.password = password === undefined ? this.loginForm.password : decrypt(password)
      this.loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)
    },
    getTenants() {
      this.loading = true
      getTenants().then(res => {
        if (res.code === 200) {
          this.tenants = res.data
        } else {
          this.$message.error('获取租户列表失败')
        }
      }).catch(_ => {
        this.$message.error('获取租户列表异常')
      }).finally(_ => {
        this.loading = false
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.cacheProjectHandld(this.loginForm.username)
          const password = this.loginForm.password
          if (this.loginForm.rememberMe) {
            Cookies.set('tenantCode', this.loginForm.tenantCode, { expires: 30 })
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove('tenantCode')
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          const form = Object.assign({}, this.loginForm, { password: encrypt(password, this.publicKey) })
          this.$store.dispatch('Login', form).then(() => {
            this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.loading = false
            this.status = false
            this.publicKey = ''
          })
        }
      })
    },
    /**
     * 滑块滑动成功
     */
    sliderSuccess() {
      this.sliderLoading = true
      getPublicKey().then(resp => {
        this.publicKey = resp.data.publicKey
        this.loginForm.uuid = resp.data.keyId
      }).catch(() => {
        this.status = false
      }).finally(() => {
        this.sliderLoading = false
      })
    },
    sliderError() {

    },
    cacheProjectHandld(username) {
      const name = localStorage.getItem('username')
      if (name !== username) {
        localStorage.setItem('username', username)
        localStorage.removeItem('currentProject')
        localStorage.removeItem('currentDept')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.logo {
  position: absolute;
  top: 20px;
  left: 20px;
  img {
    height:40px;
  }
}
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background: url("../assets/background/logo_bg.png") no-repeat center center;
  background-size: 100% 100%;

}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #00082e;
}

.login-form {
  background-color: #FFF;
  width: 400px;
  padding: 25px 25px 5px 25px;
  text-align: center;
  position: absolute;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-right: 15%;
  border-radius: 5px;

  .el-input {
    height: 38px;
    .el-input__icon {
      color: #00082e;
    }
    input {
      height: 38px;
      background-color: #b6c9f0;
      color: #00082e
    }

    input:focus {
      border-color: #00082e;
    }
  }
  /deep/ .el-input.is-focus {
    border-color: #00082e;
  }

  input::-webkit-input-placeholder{
    color:#666;
  }

  .el-checkbox__inner {

  }

  .login-checkbox {
    color: #00082e;
    .el-checkbox__inner {
        border-color: #333;
      }
    .is-checked {
      .el-checkbox__inner {
        background-color: #00082e;
        border-color: #00082e;
      }
    }
    .el-checkbox__inner:hover {
        border-color: #00082e;
      }
    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: #00082e;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .pass-state {
    color: #909399;
    margin-right: 10px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #00082e;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 34px;
  vertical-align: middle;
  cursor: pointer;
}
</style>
